/**
 * $Id: render.c 3 2010-10-02 23:39:41Z pmedia@xi-intersection.net $
 */

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------

// Globals (e.g. system functions and globally shared definitions)
#include "include/global.h"

// Game Modules
#include "include/init-deinit.h"
#include "include/input.h"
#include "include/logic.h"
#include "include/main.h"
#include "include/render.h"

// -----------------------------------------------------------------------------
// Global Variables
// -----------------------------------------------------------------------------

/**
 * Variables neccessary for FPS (Frames per Second) System
 */

int    fps;
double fpsNextGenTimeStamp;
int    fpsCurrentCounter;

// -----------------------------------------------------------------------------
// Functions
// -----------------------------------------------------------------------------

/**
 * Rendering Function
 * 
 * This functions renders everything provided by the logic unit declared as
 * scene object.
 * 
 */

void render(void) {
	double startTime, endTime, renderTime;
	char *caption;
	int t;
	
	startTime = getTimestamp();
	
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	// Render Code
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	
	glClear(GL_COLOR_BUFFER_BIT);
	
	
	SDL_GL_SwapBuffers();
	
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	// Frame Limiter
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	
	endTime = getTimestamp();
	
	if (videoSettings.fpsLimit) {
		renderTime = endTime - startTime;
		
		t = 16667 - renderTime;
		usleep(t);
	}
	
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	// FPS
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//
	
	fpsCurrentCounter += 1;
	if (fpsNextGenTimeStamp < endTime) {
		fps                 = fpsCurrentCounter;
		fpsCurrentCounter   = 0;
		fpsNextGenTimeStamp = endTime + 1000000;
		
		caption = malloc(512);
		sprintf(caption, "[A·S·T·R·O·I·D] (%i fps)", fps);
		
		SDL_WM_SetCaption(caption, caption);
		free(caption);
	}
}

